let isLiked = false;  // 标记是否已点赞
let isLoggedIn = false;  // 标记用户登录状态

document.addEventListener("DOMContentLoaded", () => {
    const urlParams = new URLSearchParams(window.location.search);
    const articleId = urlParams.get("article_id");

    if (articleId) {
        fetchArticleDetail(articleId);
        increaseViewCount(articleId);
    }

    checkUserLoginStatus();
});

function fetchArticleDetail(articleId) {
    fetch(`/api/get-article?id=${articleId}`, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === "success") {
            displayArticleDetail(data.article);
        } else {
            console.error("获取文章详情失败:", data.message);
        }
    })
    .catch(error => {
        console.error("请求文章详情失败:", error);
    });
}

function displayArticleDetail(article) {
    document.getElementById("article-title").innerText = article.title;
    document.getElementById("article-author").innerText = `作者: ${article.author}`;
    document.getElementById("article-publish-date").innerText = `发布时间: ${article.publish_date}`;
    document.getElementById("article-category").innerText = `分类: ${article.category}`;
    document.getElementById("article-content").innerHTML = article.content;
    document.getElementById("article-tags").innerText = `标签: ${article.tags.join(', ')}`;
    document.getElementById("article-view-count").innerText = `阅读数: ${article.view_count}`;
    document.getElementById("article-like-count").innerText = `点赞数: ${article.like_count}`;
    document.getElementById("article-comment-count").innerText = `评论数: ${article.comment_count}`;
}

function submitComment() {
    const commentInput = document.getElementById("comment-input");
    const newComment = commentInput.value.trim();

    if (newComment === "") {
        alert("评论内容不能为空！");
        return;
    }

    // 从 URL 中获取 article_id 参数
    const urlParams = new URLSearchParams(window.location.search);
    const articleId = urlParams.get("article_id");

    if (!articleId) {
        console.error("无法找到文章ID！");
        alert("文章ID不存在，无法提交评论。");
        return;
    }

    // 使用 URLSearchParams 构建表单数据
    const formData = new URLSearchParams();
    formData.append("articleId", articleId);
    formData.append("content", newComment);

    // 提交评论到服务器
    fetch("/api/add-comment", {
        method: "POST",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded"
        },
        body: formData
    })
    .then(response => {
        if (response.status === 401) {
            alert("请先登录后再评论！");
            throw new Error("用户未登录");
        }

        if (!response.ok) {
            return response.text().then(text => {
                throw new Error(text || '未知错误');
            });
        }

        return response.json();
    })
    .then(data => {
        if (data.success) {
            loadComments();  // 刷新评论列表
            commentInput.value = "";  // 清空输入框
        } else {
            alert("提交评论失败，请重试！");
        }
    })
    .catch(error => {
        console.error("提交评论时出错:", error);
        alert("提交评论时出错，请稍后再试！");
    });
}



function checkUserLoginStatus() {
    fetch('/api/check-login-status', {
        method: 'GET',
        headers: { 'Content-Type': 'application/json' }
    })
    .then(response => response.json())
    .then(data => {
        isLoggedIn = data.isLoggedIn;

        if (isLoggedIn) {
            // 用户已登录，启用功能按钮
            document.getElementById("like-button").disabled = false;
            document.getElementById("comment-button").disabled = false;
            document.getElementById("share-button").disabled = false;
        } else {
            // 用户未登录，禁用功能按钮
            document.getElementById("like-button").disabled = true;
            document.getElementById("comment-button").disabled = true;
            document.getElementById("share-button").disabled = true;
        }
    })
    .catch(error => console.error("登录状态检查失败:", error));
}

function handleLike() {
    if (!isLoggedIn) {
        alert("请先登录后再点赞！");
        return;
    }

    const urlParams = new URLSearchParams(window.location.search);
    const articleId = urlParams.get("article_id");

    isLiked = !isLiked;  // 切换点赞状态
    document.getElementById("like-button").innerText = isLiked ? "👍 已点赞" : "👍 点赞";

    // 发送统一的 POST 请求，根据 isLiked 状态处理点赞或取消点赞
    fetch(`/api/like-article?id=${articleId}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ isLiked: isLiked })  // 发送 isLiked 状态
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === "success") {
            document.getElementById("article-like-count").innerText = `点赞次数: ${data.new_like_count}`;
        } else {
            console.error("操作失败:", data.message);
        }
    })
    .catch(error => console.error("请求失败:", error));
}


function handleComment() {
    if (!isLoggedIn) {
        alert("请先登录后再评论！");
        return;
    }

    const commentSection = document.getElementById("add-comment");

    // 切换显示状态
    if (commentSection.style.display === "none" || commentSection.style.display === "") {
        commentSection.style.display = "block"; // 显示评论输入框
    } else {
        commentSection.style.display = "none"; // 隐藏评论输入框
    }
}

function handleShare() {
    if (!isLoggedIn) {
        alert("请先登录后再分享！");
        return;
    }

    // 处理分享功能
    const textToCopy = window.location.href; // 获取当前页面链接

    if (navigator.clipboard) {
        // 如果浏览器支持 Clipboard API
        navigator.clipboard.writeText(textToCopy)
            .then(() => {
                alert("文章链接已复制，可分享给好友！");
            })
            .catch(error => {
                console.error("分享失败:", error);
                alert("复制失败，请手动复制链接！");
            });
    } else {
        // 如果浏览器不支持 Clipboard API，使用 document.execCommand 作为回退
        console.warn("Clipboard API 不受支持，使用 document.execCommand");

        // 创建一个临时的 textarea 元素
        const textarea = document.createElement('textarea');
        textarea.value = textToCopy;
        document.body.appendChild(textarea);

        // 选择 textarea 中的内容
        textarea.select();
        textarea.setSelectionRange(0, 99999); // 对于移动设备上的支持

        try {
            // 执行复制命令
            const successful = document.execCommand('copy');
            if (successful) {
                alert("文章链接已复制，可分享给好友！");
            } else {
                alert("复制失败，请手动复制链接！");
            }
        } catch (err) {
            console.error("复制失败:", err);
            alert("复制失败，请手动复制链接！");
        }

        // 删除临时的 textarea 元素
        document.body.removeChild(textarea);
    }
}

function increaseViewCount(articleId) {
    fetch(`/api/increase-view-count?id=${articleId}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' }
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === "success") {
            console.log("浏览量增加成功");
        } else {
            console.error("增加浏览量失败:", data.message);
        }
    })
    .catch(error => console.error("请求增加浏览量失败:", error));
}

function loadComments() {
    // 从 URL 中获取 article_id 参数
    const urlParams = new URLSearchParams(window.location.search);
    const articleId = urlParams.get("article_id");

    if (!articleId) {
        console.error("无法找到文章ID！");
        alert("无法加载评论，因为文章ID不存在。");
        return;
    }

    fetch(`/api/get-comments?articleId=${articleId}`)
   .then(response => response.json())
   .then(data => {
       const commentsList = document.getElementById("comments-list");
       commentsList.innerHTML = ""; // 清空已有的评论

       if (data.success) {
           data.comments.forEach(comment => {
               const commentElement = document.createElement("div");
               commentElement.classList.add("comment");

               // 确保头像路径有效
               const avatarUrl = comment.avatar;
               const imgElement = document.createElement("img");
               imgElement.classList.add("avatar");
               imgElement.alt = `${comment.username} 的头像`;
               imgElement.src = avatarUrl;

               // 检查头像是否能加载
               imgElement.onerror = () => {
                   imgElement.src = './rescource/avatar/default-avatar';  // 默认头像
               };

               commentElement.innerHTML = `
                   <div class="comment-details">
                       <p class="username">${comment.username}</p>
                       <p class="comment-text">${comment.content}</p>
                       <p class="timestamp">${comment.timestamp}</p>
                   </div>
               `;
               
               commentElement.prepend(imgElement);  // 将头像插入到评论元素中
               commentsList.appendChild(commentElement);
           });
       } else {
           // alert("加载评论失败，请稍后再试！");
       }
   })
   .catch(error => {
       console.error("获取评论时出错:", error);
       // alert("评论加载失败，请稍后再试！");
   });

}

